package rule

import (
	"regexp"
	"time"
)

func init() {
	Register(&dateTimeRule{reg: regexp.MustCompile(`^[1-9]{1}\d{3}-[0-1]{1}[0-9]{1}-[0-3]{1}[0-9]{1} ([0-1]{1}[0-9]{1}|2{1}[0-3]{1}):[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$`)})
}

type dateTimeRule struct {
	reg *regexp.Regexp
}

func (d dateTimeRule) Name() string {
	return "datetime"
}

type iTime interface {
	Date() (year int, month time.Month, day int)
	IsZero() bool
}

func (d dateTimeRule) Check(in *RuleInput) (err error) {
	if v, ok := in.Value.(iTime); ok && !v.IsZero() {
		return
	}
	if v, ok := in.Value.(string); ok && v != "" && d.reg.FindStringIndex(v) != nil {
		return
	}
	return in.Error()
}
